package ve.com.ucv.changedetection.model;

import org.w3c.dom.Node;
import ve.com.ucv.changedetection.objects.Attribute;
import ve.com.ucv.changedetection.objects.TreeNode;

/**
 * Created with IntelliJ IDEA.
 * User: Jose Manuel Aguirre
 * Date: 16/10/12
 * Time: 02:20 PM
 * To change this template use File | Settings | File Templates.
 */
public class TreeBuilder {
    public static TreeNode buildAbstractTree(Node domTree, String root, int depth){
        //CREATING TREENODE INSTANCE
        TreeNode abstractTree = new TreeNode();
        int hashValue = 0;

        abstractTree.setNodeName(domTree.getNodeName());
        abstractTree.setNodeValue(domTree.getNodeValue());
        abstractTree.setNodeType(root + ";" + domTree.getNodeName());
        abstractTree.setDepth(depth);
        depth++;

        //SETEANDO LOS ATRIBUTOS
        if (domTree.getAttributes().getLength() != 0){
            for(int i = 0; i < domTree.getAttributes().getLength(); i++){
                Attribute attribute = new Attribute();
                attribute.setAttName(domTree.getAttributes().item(i).getNodeName());
                attribute.setAttValue(domTree.getAttributes().item(i).getNodeValue());
                abstractTree.setAttribute(attribute);
            }
        }

        if (domTree.hasChildNodes()){
            for (int index = 0; index < domTree.getChildNodes().getLength(); index++){
                abstractTree.setChild(buildAbstractTree(domTree.getChildNodes().item(index), abstractTree.getNodeType(), depth));
                hashValue = hashValue + abstractTree.getChild(index).getHashValue();
            }
            abstractTree.setHashValue(hashValue);
        }else{
            abstractTree.setHashValue(domTree.getNodeValue().hashCode());
        }
        return abstractTree;
    }


}
